import { uniqueId } from '.'
import { PostMessageType, type PostMessageEvent, Certificate } from './types'

let certificate = Certificate.NONE

export function registerCertificate(value: Certificate) {
  certificate = value
}

let extensionId: string | null = null

chrome.runtime?.onMessage.addListener((event: PostMessageEvent, sender) => {
  if (event?.uniqueId === uniqueId) {
    if (event.type === PostMessageType.HEARTBEAT) {
      certificate === event.data &&
        sendMessage({ type: PostMessageType.HEARTBEAT, data: certificate })
      return void 0
    }
    if (event.type === PostMessageType.CONNECT) {
      extensionId = sender.id!
    }
    emitMessage(event.type, event.data)
  }
  return void 0
})

const pool = new Map<any, Set<(data: any) => void>>()

function emitMessage(type: PostMessageType, data: any) {
  pool.get(type)?.forEach((handler) => handler(data))
}

/**
 * 监听其它端发送的信息
 * @param type 事件类型
 * @param handler 事件回调
 */
export function onMessage(type: PostMessageEvent['type'], handler: (data: any) => void) {
  let set = pool.get(type)
  if (!set) pool.set(type, (set = new Set()))
  set.add(handler)
}

/**
 * 取消对其它端信息的监听
 * @param type 事件类型
 * @param handler 事件回调
 */
export function offMessage(type: PostMessageType, handler: any) {
  pool.get(type)?.delete(handler)
}

/**
 * 向服务端发送信息
 * @param event 事件信息
 */
export function sendMessage(event: PostMessageEvent) {
  console.log({ event })
  extensionId
    ? chrome.runtime.sendMessage(extensionId, { uniqueId, ...event })
    : chrome.runtime.sendMessage({ uniqueId, ...event })
}
